#include "dbsetwindow.h"
#include "ui_dbsetwindow.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QDebug>
#include <QMessageBox>
#include <QHostInfo>
DBSetWindow::DBSetWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DBSetWindow)
{
    ui->setupUi(this);
    initWindow();
}

DBSetWindow::~DBSetWindow()
{
    delete ui;
}

void DBSetWindow::initWindow()
{
    QStringList dris = QSqlDatabase::drivers();
    ui->deriverComboBox->addItems(dris);
    QString name = QHostInfo::localHostName();
    QHostInfo hinfo= QHostInfo::fromName(name);
    QList<QHostAddress> addrs = hinfo.addresses();
    for(auto  addr : addrs)
    {
        if(addr.protocol() == QAbstractSocket::IPv4Protocol)
        {
            ui->ipComboBox->addItem(addr.toString());
        }
    }
}

void DBSetWindow::on_lookButton_clicked()
{
    filename = QFileDialog::getOpenFileName(this,"请选择使用的数据库文件",".",
                                                    "db(*.db)");
    QFileInfo info(filename);
    ui->nameLineEdit->setText(info.fileName());
}

void DBSetWindow::on_deriverComboBox_currentIndexChanged(const QString &arg1)
{
    if(arg1 == "QSQLITE")
    {
        ui->userLineEdit->setEnabled(false);
        ui->passwdLineEdit->setEnabled(false);
    }
    else
    {
        ui->userLineEdit->setEnabled(true);
        ui->passwdLineEdit->setEnabled(true);
    }
}

void DBSetWindow::on_openButton_clicked()
{
   db = QSqlDatabase::addDatabase(ui->deriverComboBox->currentText());
   db.setHostName(ui->ipComboBox->currentText());
   db.setDatabaseName(filename);
   bool ret = db.open();  //打开数据库是否成功
   if(ret)
   {
        QMessageBox::information(this,"提示","数据库打开成功",QMessageBox::Ok);
        emit changeTableWindow();
   }
   else
   {
        QMessageBox::information(this,"提示","数据库打开失败",QMessageBox::Ok);
   }
}

void DBSetWindow::on_closeButton_clicked()
{
    db.close();
}
